<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes class="default-theme">
        <pane>
          <el-col size="84">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                     label-width="68px">
              <el-form-item style="margin-left: -28px" label="姓名" prop="nickName">
                <el-input v-model="queryParams.nickName" placeholder="请输入姓名" clearable style="width: 140px"
                          @keyup.enter.native="handleQuery"/>
              </el-form-item>
              <el-form-item style="margin-left: 0px" label="身份证号" prop="idCard">
                <el-select
                  v-model="queryParams.idCard"
                  filterable
                  remote
                  :remote-method="handleSearchCkIdCard"
                  placeholder="请输入身份证后6位"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.idCard"
                    :label="formatIdCard(item.idCard)"
                    :value="item.idCard"
                  />
                </el-select>
              </el-form-item>
              <el-form-item style="margin-left: -15px" label="手机号" prop="phonenumber">
                <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号" clearable style="width: 160px"
                          @keyup.enter.native="handleQuery"/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                           v-hasPermi="['system:user:add']">新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                           @click="handleDelete" v-hasPermi="['system:user:remove']">删除
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                           v-hasPermi="['system:user:export']">导出
                </el-button>
              </el-col>
            </el-row>

            <!-- 列表 -->
            <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" align="center"/>
              <el-table-column label="姓名" align="center" key="nickName" prop="nickName"
                               :show-overflow-tooltip="true" fixed="left"/>
              <el-table-column label="身份证号" align="center" key="idCard" prop="idCard"
                               width="180"/>
              <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber"
                               width="120"/>
              <el-table-column label="航班" align="center" key="flightNo" prop="flightNo"
                               width="160">
                <template slot-scope="scope">
                  <div style="display: flex;justify-content: center">
                    <span class="el-tag el-tag--success el-tag--medium el-tag--light">
                    {{ scope.row.flightNo }}
                  </span>
                    <svg-icon v-if="scope.row.transferFlightNo != '无'" icon-class="jiantou" style="margin-top: 6px;"/>
                    <span v-if="scope.row.transferFlightNo != '无'"
                          class="el-tag el-tag--warning el-tag--medium el-tag--light" >
                    {{scope.row.transferFlightNo}}
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="岗位" align="center" key="postName" prop="postName"
                               width="80">
                <template slot-scope="scope">
                  <span style="color: #1f77d5" >{{ scope.row.postName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="值机是否登机" align="center" key="zdBoardingStatus" width="140">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.boarding_status" :value="scope.row.zdBoardingStatus"/>
                </template>
              </el-table-column>
              <el-table-column label="中转是否登机" align="center" key="zzBoardingStatus" width="140">
                <template slot-scope="scope">
                  <dict-tag v-if="scope.row.transferFlightNo != '无'" :options="dict.type.boarding_status" :value="scope.row.zzBoardingStatus"/>
                  <span v-else >无需中转</span>
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center" key="status">
                <template slot-scope="scope">
                  <span v-if="scope.row.status == '0'"
                        class="el-tag el-tag--primary el-tag--medium el-tag--light">正常</span>
                  <span v-if="scope.row.status == '1'"
                        class="el-tag el-tag--danger el-tag--medium el-tag--light">停用</span>
                </template>
              </el-table-column>
              <el-table-column label="更新时间" align="center" prop="updateTime" width="160">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.updateTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" align="center" width="160"
                               class-name="small-padding fixed-width">
                <template slot-scope="scope" v-if="scope.row.userId !== 1">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                             v-hasPermi="['system:user:edit']">修改
                  </el-button>
<!--                  <el-button size="mini" type="text" icon="el-icon-key" @click="handleResetPwd(scope.row)"
                             v-hasPermi="['system:user:resetPwd']">重置密码
                  </el-button>-->
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList"/>
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item style="margin-left: -10px" label="姓名" prop="nickName">
              <el-select
                v-model="form.nickName"
                filterable
                placeholder="请选择乘客"
                @change="handleChange"
              >
                <el-option
                  v-for="item in ckBaseInfo"
                  :key="item.ckBaseId"
                  :label="item.ckName"
                  :value="item.ckBaseId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input :disabled="true" v-model="form.idCard" placeholder="身份证号" maxlength="18"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phonenumber">
              <el-input :disabled="true" v-model="form.phonenumber" placeholder="手机号" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input :disabled="true" v-model="form.email" placeholder="邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="登录账号" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入账号" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="登录密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入密码" type="password" maxlength="20" show-password/>
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row>
          <el-col :span="24">
            <el-form-item label="航班" prop="flightNo">
              <el-select style="width: 480px" v-model="form.flightNo" placeholder="请选择航班" @change="changeFlightNo">
                <el-option v-for="item in flightOptions"
                           :key="item.key"
                           :label="formartLabel(item.labelPrefix, item.labelSuffix)"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="中转航班" prop="transferFlightNo">
              <el-select style="width: 480px" :disabled="isShow" v-model="form.transferFlightNo" placeholder="请选择航班">
                <el-option v-for="item in transferFlightOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位" prop="postId">
              <el-select  v-model="form.postId" placeholder="请选择岗位">
                <el-option v-for="item in postOptions" :key="item.postId"
                           :label="item.postName" :value="item.postId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleId">
              <el-select  v-model="form.roleId" placeholder="请选择角色">
                <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col v-if="this.form.status != undefined" :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPassenger,
  getPassenger,
  delPassenger,
  addPassenger,
  updatePassenger,
  resetUserPwd,
  getCkBaseInfo
} from "@/api/ground/passenger";
import { getCkIdCardInfo } from "@/api/ckxl/ck";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {Splitpanes, Pane} from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { debounce } from 'lodash';

export default {
  name: "Passenger",
  dicts: ['sys_normal_disable', 'sys_user_sex', 'boarding_status'],
  components: {Treeselect, Splitpanes, Pane},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/passenger/people/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 表单校验
      rules: {
        /*userName: [
          {required: true, message: "账号不能为空", trigger: "blur"},
          /!*{min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur'}*!/
        ],*/
        nickName: [
          {required: true, message: "姓名不能为空", trigger: "blur"}
        ],
        idCard: [
          {required: true, message: '请输入身份证号码', trigger: 'blur'},
          {
            pattern: /^[1-9]\d{5}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/,
            message: '身份证号码格式不正确', trigger: 'blur'
          }
        ],
        flightNo: [
          {required: true, message: "请选择航班", trigger: "change"}
        ],
        transferFlightNo: [
          {required: true, message: "请选择中转航班", trigger: "change"}
        ],
        postId: [
          {required: true, message: "请选择岗位", trigger: "change"}
        ],
        roleId: [
          {required: true, message: "请选择角色", trigger: "change"}
        ],
        /*password: [
          {required: true, message: "用户密码不能为空", trigger: "blur"},
          {min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur'},
          {pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur"}
        ],*/
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号",
            trigger: "blur"
          }
        ]
      },
      //航班编号
      flightOptions: [],
      //中转航班编号
      transferFlightOptions:[],
      // 选中数组
      nickNames: [],
      //默认新增
      addFlag:true,
      isShow:true,
      ckBaseInfo:{},
      options: [{
        label:"",
        value:""
      }],
    };
  },
  watch: {},
  created() {
    this.getList();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
    this.getCkBase();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listPassenger(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.nickNames = selection.map(item => item.nickName);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.addFlag = true;
      this.reset();
      getPassenger().then(response => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.flightOptions = response.flightNos;
        this.open = true;
        this.title = "添加乘客";
        this.form.password = this.initPassword;
      });
    },

    // 防抖处理（500ms内仅触发一次）
    getCkBase() {
      //查询乘客基本信息
      getCkBaseInfo().then(response => {
        this.ckBaseInfo = response.data;
      }).catch(() => {
      });
    },

    // 选中乘客基本信息
    handleChange(val){
      const item = this.ckBaseInfo.find(item => item.ckBaseId == val)
      this.$set(this.form, 'idCard', item.ckIdCard);
      this.$set(this.form, 'phonenumber', item.ckPhoneNumber);
      this.$set(this.form, 'email', item.ckEmail);
      this.$set(this.form, 'nickName', item.ckName);
      this.$set(this.form, 'ckBaseId', item.ckBaseId);
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      if(row.zdBoardingStatus == '1'){
        this.$modal.msgError("已登机的乘客，不允许修改信息！");
        return;
      }
      this.addFlag = false;
      this.reset();
      const userId = row.userId || this.ids;
      getPassenger(userId).then(response => {
        this.form = response.data;
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.flightOptions = response.flightNos;
        this.$set(this.form, "postId", response.postIds[0]);
        this.$set(this.form, "roleId", response.roleIds[0]);
        this.open = true;
        this.title = "修改乘客";
        this.form.password = "";
        this.getTransferFlightStatus(row);
      });
    },

    /** 获取航班状态 */
    getTransferFlightStatus(row){
      // if(row.isTransfer == '1'){
      //   this.isShow = true;
      //   this.$set(this.form,"transferFlightNo",'无');
      // }else {
      //   this.isShow = false;
      // }
      // if(row.transferFlightNo == null){
      //   this.$set(this.form,"transferFlightNo",'无');
      // }
    },

    //起始航班调整
    changeFlightNo(flightNo){
      if(flightNo != 'MU2811'){
        this.$set(this.form,"transferFlightNo",'无');
      }else if(flightNo == 'MU2811'){
        this.form.transferFlightNo='CA1901';
        this.transferFlightOptions=[ {
          label: 'CA1901 北京-大兴国际机场 ' + '→' + '乌鲁木齐-地窝堡国际机场T3 14:00',
          value: 'CA1901'
        }]
      }/*else if(flightNo == 'MF8562'){
        this.form.transferFlightNo='CZ6714';
        this.transferFlightOptions=[ {
          label: 'CZ6714 北京-大兴国际机场 '+ '→' + '三亚-凤凰国际机场T1 14:10',
          value: 'CZ6714'
        }]
      }*/
    },

    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      if(row.zdBoardingStatus == '1'){
        this.$modal.msgError("已登机的乘客，不允许重置密码！");
        return;
      }
      this.$prompt('请输入"' + row.nickName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({value}) => {
        resetUserPwd(row.userId, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          var peopleNum = this.$store.state.user.peopleNum;
          if (this.form.userId != undefined) {
            updatePassenger(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPassenger(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              peopleNum = peopleNum + 1;
              this.$set(this.$store.state.user, "peopleNum", peopleNum);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var peopleNum = this.$store.state.user.peopleNum;
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除乘客姓名为"' + this.nickNames + '"的数据项？').then(function () {
        return delPassenger(userIds);
      }).then(() => {
        peopleNum = peopleNum - 1;
        this.getList();
        this.$set(this.$store.state.user, "peopleNum", peopleNum);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('passenger/people/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },

    //完善航班信息
    formartLabel(labelPrefix, labelSuffix){
      let arrow = '→'
      return labelPrefix + arrow + labelSuffix;
    },

    // 防抖处理（500ms内仅触发一次）
    handleSearchCkIdCard: debounce(function(query) {
      if(query.trim().length >6){
        const keyword = query.trim().slice(0, 6).toUpperCase();
        this.$modal.msgError("最多只能输入6个字符");
        this.queryParams.passengerIdCard = keyword;
        return;
      }
      // 校验格式：6位数字或X
      if (!/^[0-9X]{6}$/.test(query.trim())) {
        this.options = [];
        return;
      }
      const lastSixIdNum = query.trim();
      getCkIdCardInfo(lastSixIdNum).then(response => {
        if (response.data != null) {
          this.options = response.data
        }
      }).catch(() => {
        this.options = [];
      });
    }, 500),

    // 格式化显示身份证号（如：410*****123456）
    formatIdCard(idCard) {
      if(idCard != null){
        return idCard.replace(/(\d{4})\d+(\d{6})/, '$1*****$2');
      }
    },

  }
};
</script>
